package com.example.jnuexperiment2025;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.jnuexperiment2025.dataop.Book;
import com.example.jnuexperiment2025.dataop.DataStorage;
import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

public class BookListFragment extends Fragment implements RecyclerViewBookAdpater.OnItemActionCallback {

    private List<Book> bookList;
    private RecyclerViewBookAdpater adapter;
    private int currentPosition;
    private DataStorage dataStorage;

    private final ActivityResultLauncher<Intent> addLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    Intent data = result.getData();
                    String title = data.getStringExtra("title");
                    bookList.add(currentPosition + 1, new Book(title, R.drawable.book_no_name));
                    adapter.notifyItemInserted(currentPosition + 1);
                }
            });

    private final ActivityResultLauncher<Intent> updateLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    Intent data = result.getData();
                    String title = data.getStringExtra("title");
                    Book bookToUpdate = bookList.get(currentPosition);
                    bookToUpdate.setTitle(title);
                    adapter.notifyItemChanged(currentPosition);
                }
            });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_book_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        dataStorage = new DataStorage();
        bookList = dataStorage.loadData(requireContext());

        if (bookList.isEmpty()) {
            bookList = new ArrayList<>();
            bookList.add(new Book(getString(R.string.book_software_project_management), R.drawable.book_1));
            bookList.add(new Book(getString(R.string.book_innovation_engineering), R.drawable.book_2));
            bookList.add(new Book(getString(R.string.book_information_security_math), R.drawable.book_3));
        }

        RecyclerView recyclerView = view.findViewById(R.id.recycler_view_books);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RecyclerViewBookAdpater(bookList);
        adapter.setCallback(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onPause() {
        super.onPause();
        dataStorage.saveData(requireContext(), (ArrayList<Book>) bookList);
    }

    @Override
    public void onAddItem(int position) {
        currentPosition = position;
        Intent intent = new Intent(requireContext(), BookDetailsActivity.class);
        addLauncher.launch(intent);
    }

    @Override
    public void onUpdateItem(int position) {
        currentPosition = position;
        Intent intent = new Intent(requireContext(), BookDetailsActivity.class);
        Book book = bookList.get(position);
        intent.putExtra("title", book.getTitle());
        updateLauncher.launch(intent);
    }

    @Override
    public void onDeleteItem(int position) {
        new AlertDialog.Builder(requireContext())
                .setTitle(R.string.dialog_delete_title)
                .setMessage(R.string.dialog_delete_message)
                .setPositiveButton(R.string.dialog_yes, (dialog, which) -> {
                    bookList.remove(position);
                    adapter.notifyItemRemoved(position);
                })
                .setNegativeButton(R.string.dialog_no, null)
                .create()
                .show();
    }
}

